/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:26
 * @LastEditTime: 2021-06-12 20:42:19
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \lua\luadb\rows.go
 * hnxr
 */
package luadb

import (
	"database/sql"

	lua "github.com/yuin/gopher-lua"
)

func checkRows(l *lua.LState) *sql.Rows {
	ud := l.CheckUserData(1)
	if v, ok := ud.Value.(*sql.Rows); ok {
		return v
	}
	l.ArgError(1, "rows expected")
	return nil
}

func queryRows(query Queryer, sql string, l *lua.LState) int {
	//rows := []map[string]interface{}{}
	rows, err := query.Raw(sql).Rows()
	if err != nil {
		l.Push(lua.LString(err.Error()))
		return 1
	}
	ud := l.NewUserData()
	ud.Value = rows
	l.SetMetatable(ud, l.GetTypeMetatable(luaRowsTypeName))
	l.Push(ud)
	return 1
}

//newRows .
func newRows(l *lua.LState) int {
	n := l.GetTop()
	if n < 1 {
		l.Push(lua.LString("Paramster error"))
		return 1
	}
	db := "default"
	sql := l.CheckString(1)
	if n > 1 {
		db = sql
		sql = l.CheckString(2)
	}

	mdb, ok := boss.dbs[db]
	if !ok {
		l.Push(lua.LString("No this database:" + db))
		return 1
	}

	return queryRows(mdb, sql, l)
}

//rowsNext 下一行
func rowsNext(l *lua.LState) int {
	rows := checkRows(l)
	isHaveNext := rows.Next()
	l.Push(lua.LBool(isHaveNext))
	if !isHaveNext {
		rows.Close() //自动关闭
		//logs.Info("Rows auto closed.")
	}
	return 1
}

//rowsClose 关闭
func rowsClose(l *lua.LState) int {
	rows := checkRows(l)
	err := rows.Close()
	if err != nil {
		l.Push(lua.LString(err.Error()))
		return 1
	}
	return 0
}

//rowsData 获取每行的数据
func rowsData(l *lua.LState) int {
	rows := checkRows(l)
	tab := l.NewTable()
	err := row2table(rows, tab, true)
	if err != nil {
		l.Push(lua.LString(err.Error()))
		return 1
	}
	l.Push(tab)
	return 1
}
